package pl.com.qapps.datastore.berkeley;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import pl.com.qapps.datastore.berkeley.impl.EntityBindings;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityTranslator;
import com.google.appengine.api.datastore.Key;
import com.google.storage.onestore.v3.OnestoreEntity.EntityProto;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;

@Deprecated
public class GetRequestDep extends BaseRequest<Map<Key, Entity>> {

	private Iterable<Key> keys;
	private final List<DatabaseEntry> keysData = new LinkedList<>();

	void setKeys(Iterable<Key> keys) {
		if (keys == null)
			throw new IllegalArgumentException("keys cannot be null");
		this.keys = keys;
		this.keysData.clear();
	}

	@Override
	Map<Key, Entity> run(Store store, Transaction txn) {
		Map<Key, Entity> entities = new HashMap<>();
		Database db = store.getEntityDb();
		for (DatabaseEntry keyData : keysData) {
			// System.out.println("GetRequestDep: getting using key"
			// + Arrays.toString(keyData.getData()) + " length:"
			// + keyData.getSize());
			DatabaseEntry entityData = new DatabaseEntry();
			OperationStatus result = db.get(txn, keyData, entityData,
					LockMode.READ_COMMITTED);
			if (result == OperationStatus.SUCCESS) {
				Entity entity = EntityTranslator
						.createFromPb(EntityBindings.ENTITY_BINDING.entryToObject(
								keyData, entityData));
				entities.put(entity.getKey(), entity);
			}
		}
		return entities;
	}

	@Override
	void init(Store store) {
		keysData.clear();
		for (Key key : keys) {
			DatabaseEntry keyData = new DatabaseEntry();
			EntityBindings.ENTITY_KEY_BINDING.objectToEntry(key, keyData);
			keysData.add(keyData);
		}
	}
}
